import axios from "axios";
import router from "../router";
import {
  Message,
  Loading
} from "element-ui";
import {
  getToken
} from "@/utils/auth";
const SUCCESS = 0;
const ERROR = 1;
const AUTH = 10;
axios.defaults.timeout = 10000;
axios.defaults.baseURL = "/api";
axios.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded";
let loadingInstance = null;
axios.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    loadingInstance = Loading.service();
    config.headers["authorization"] = getToken(); // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
    return config;
  },
  function (error) {
    if (loadingInstance) {
      loadingInstance.close();
      loadingInstance = null
    }
    return Promise.reject(error);
  }
);
axios.interceptors.response.use(
  function (response) {
    if (loadingInstance) {
      loadingInstance.close();
      loadingInstance = null
    }
    if (!(response.status >= 200 && response.status < 300)) {
      return response;
    }
    if (response.data.code === AUTH) {
      Message({
        message: response.data.msg,
        type: "error",
        center: true,
        duration: 5 * 1000
      });
      router.replace({
        name: "Login"
      });
      throw response.data.msg;
    }

    if (response.data.code === ERROR) {
      Message({
        message: response.data.msg,
        type: "error",
        center: true,
        duration: 5 * 1000
      });
      throw response.data.msg;
    }
    return response.data.data;
  },
  function (error) {

    if (loadingInstance) {
      loadingInstance.close();
      loadingInstance = null
    }
    Message({
      message: "error",
      type: "error",
      center: true,
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

export default axios;